# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
import shutil
from cerbero.utils import needs_xcode8_sdk_workaround

GLIB_CONFIG_UNVERSAL='''\
#ifdef __i386__
#include "i386/glibconfig.h"
#elif defined(__ppc__)
#include "ppc/glibconfig.h"
#elif defined(__x86_64__)
#include "x86_64/glibconfig.h"
#elif defined(__arm__)
#include "arm/glibconfig.h"
#elif defined(__arm64__)
#include "arm64/glibconfig.h"
#else
#error "Unsupported Architecture"
#endif
'''

class Recipe(recipe.Recipe):
    name = 'glib'
    version = '2.50.3'
    stype = SourceType.TARBALL
    url = 'http://ftp.acc.umu.se/pub/GNOME/sources/glib/2.50/glib-%(version)s.tar.xz'
    licenses = [License.LGPLv2Plus]
    config_sh = 'sh autogen.sh'
    configure_options = '--with-pcre=internal --disable-libmount --enable-dtrace=no '
    deps = ['libffi', 'zlib']
    can_use_configure_cache = False
    patches = ["glib/0001-Let-user-disable-Cocoa-and-Carbon-support-on-demand.patch",
               "glib/0002-Optionally-revert-to-the-old-pre-2.28-URI-handler-co.patch",
               "glib/0003-Add-support-for-loading-GIO-modules-from-the-distro-.patch",
               "glib/0004-Allow-for-a-second-distro-GIO-module-path-as-used-on.patch",
               "glib/0005-Blacklist-the-bamf-GIO-module.patch",
               "glib/0006-giomodule-do-not-try-to-load-modules-from-gio-module.patch",
               "glib/0008-gdbus-codgen-Use-a-proper-shebang-in-the-generator.patch",
               "glib/0009-Unhide-_g_io_modules_ensure_extension_points_registe.patch",
               'glib/0015-Implementation-of-Cocoa-event-loop-integration-in-GM.patch',
               'glib/0016-gmessages-Fix-compilation-on-Android.patch',
               'glib/0017-GSocket-Fix-race-conditions-on-Win32-if-multiple-thr.patch',
               'glib/0018-Check-for-RTLD_LAZY-and-others-in-configure.patch',
               'glib/0018-Don-t-use-RTLD_DEFAULT-on-Android-for-g_module_self.patch',
               'glib/0019-gmain-Fix-erroneous-if-condition-when-dtrace-is-disa.patch'
              ]

    files_libs = [
        'libglib-2.0', 'libgio-2.0', 'libgmodule-2.0', 'libgobject-2.0',
        'libgthread-2.0']
    files_bins = ['gsettings', 'gdbus', 'gio-querymodules', 'glib-compile-schemas']
    platform_files_schemas = {
        Platform.WINDOWS: ['share/glib-2.0/schemas'],
        Platform.DARWIN: ['share/glib-2.0/schemas'],
        Platform.IOS: ['share/glib-2.0/schemas'],
    }
    #FIXME: Fill it when needed
    #files_gio = ['lib/gio/modules']
    files_devel = [
        'bin/glib-gettextize',
        'bin/glib-mkenums',
        'bin/glib-compile-resources%(bext)s',
        'bin/glib-genmarshal%(bext)s',
        'bin/gresource%(bext)s',
        'bin/gdbus-codegen',
        'lib/glib-2.0/include',
        'lib/pkgconfig/gio-2.0.pc',
        'lib/pkgconfig/glib-2.0.pc',
        'lib/pkgconfig/gmodule-2.0.pc',
        'lib/pkgconfig/gmodule-export-2.0.pc',
        'lib/pkgconfig/gmodule-no-export-2.0.pc',
        'lib/pkgconfig/gobject-2.0.pc',
        'lib/pkgconfig/gthread-2.0.pc',
        'include/glib-2.0',
        'share/aclocal/glib-2.0.m4',
        'share/aclocal/glib-gettext.m4'
        ]
    platform_files_devel = {
        Platform.WINDOWS: ['lib/pkgconfig/gio-windows-2.0.pc', 'include/gio-win32-2.0'],
        Platform.LINUX: ['lib/pkgconfig/gio-unix-2.0.pc', 'include/gio-unix-2.0'],
        Platform.ANDROID: ['lib/pkgconfig/gio-unix-2.0.pc', 'include/gio-unix-2.0'],
        Platform.DARWIN: ['lib/pkgconfig/gio-unix-2.0.pc', 'include/gio-unix-2.0'],
        Platform.IOS: ['lib/pkgconfig/gio-unix-2.0.pc', 'include/gio-unix-2.0'],
    }

    files_lang = ['glib20']

    def _set_gio_flags(self, path1=None, path2=None, use_old_uri_scheme=False):
        self.append_env['CFLAGS'] = self._gio_flags(path1, path2, use_old_uri_scheme)

    def _gio_flags(self, path1=None, path2=None, use_old_uri_scheme=False):
        flags = ''
        def escape(path):
            return '\\"%s\\"' % path
        if path1 is not None:
            flags += ' -DGST_SDK_GLIB_GIO_DISTRO_GIO_MODULE_PATH=%s' % escape(path1)
        if path2 is not None:
            flags += ' -DGST_SDK_GLIB_GIO_DISTRO_GIO_MODULE_PATH2=%s' % escape(path2)
        if use_old_uri_scheme:
            flags += ' -DGST_SDK_GLIB_GIO_OLD_URI_SCHEME_HANDLERS=1'
        return flags

    def prepare(self):
        if needs_xcode8_sdk_workaround(self.config):
            self.append_env['ac_cv_func_mkostemp'] = 'no'
        if self.config.target_platform != Platform.WINDOWS:
            self.configure_options += ' --enable-static'
        if self.config.target_platform != Platform.LINUX:
            self.configure_options += ' --disable-gtk-doc '
            # Disable valgrind code on non-Linux, in the best case it just
            # gives us compiler errors :)
            self.append_env['CFLAGS'] = ' -DNVALGRIND=1 '
        if self.config.target_platform == Platform.ANDROID:
            # Hack to fix building of the glib/tests/private test
            self.make = '%s private_LDFLAGS=""' % self.make
        elif self.config.target_platform == Platform.WINDOWS:
            self.configure_options += ' --with-libiconv=gnu'
            self.append_env['CFLAGS'] = ' -DMINGW_HAS_SECURE_API=1 '
        elif self.config.target_platform in [Platform.DARWIN, Platform.IOS]:
            self.files_devel.append(os.path.join('lib', 'glib-2.0', 'include', '*', 'glibconfig.h'))

            arch = self.config.target_arch
            if arch == Architecture.X86:
                arch = 'i386'
            elif arch == Architecture.ARM64:
                arch = 'arm64'
            elif Architecture.is_arm(arch):
                arch = 'arm'
            extra_flags = ''
            if self.config.target_platform == Platform.IOS:
                # Disable mac OS X specifics
                extra_flags = '-DGST_SDK_IOS=1'
                self.configure_options += ' --disable-carbon --disable-modular-tests --disable-cocoa'

            self.append_env['CFLAGS']="-DHAVE_STRNDUP %s" % extra_flags

        elif self.config.target_platform == Platform.LINUX:
            path1 = '/usr/lib/gio/modules'
            path2 = None
            use_old_uri_scheme = False
            self.configure_options += ' --disable-selinux'
            # Old Debian/Ubuntu
            if self.config.target_distro_version in [DistroVersion.DEBIAN_SQUEEZE,
                                                     DistroVersion.UBUNTU_LUCID,
                                                     DistroVersion.UBUNTU_MAVERICK]:
                use_old_uri_scheme = True
            # Ubuntu
            elif self.config.target_distro_version in [DistroVersion.UBUNTU_NATTY,
                                                       DistroVersion.UBUNTU_ONEIRIC,
                                                       DistroVersion.UBUNTU_PRECISE,
                                                       DistroVersion.UBUNTU_QUANTAL,
                                                       DistroVersion.UBUNTU_RARING,
                                                       DistroVersion.UBUNTU_SAUCY,
                                                       DistroVersion.UBUNTU_TRUSTY,
                                                       DistroVersion.UBUNTU_UTOPIC,
                                                       DistroVersion.UBUNTU_VIVID,
                                                       DistroVersion.UBUNTU_WILY,
                                                       DistroVersion.UBUNTU_XENIAL]:
                if self.config.target_arch == Architecture.X86:
                    path2 = '/usr/lib/i386-linux-gnu/gio/modules'
                elif self.config.target_arch == Architecture.X86_64:
                    path2 = '/usr/lib/x86_64-linux-gnu/gio/modules'
            # Debian
            elif self.config.target_distro_version in [DistroVersion.DEBIAN_WHEEZY,
                                                       DistroVersion.DEBIAN_JESSIE,
                                                       DistroVersion.DEBIAN_STRETCH,
                                                       DistroVersion.DEBIAN_BUSTER]:
                if self.config.target_arch == Architecture.X86:
                    path1 = '/usr/lib/i386-linux-gnu/gio/modules'
                elif self.config.target_arch == Architecture.X86_64:
                    path1 = '/usr/lib/x86_64-linux-gnu/gio/modules'
            # RedHat
            elif self.config.target_distro == Distro.REDHAT:
                if self.config.target_arch == Architecture.X86_64:
                    path1 = '/usr/lib64/gio/modules/'
            # Suse
            elif self.config.target_distro == Distro.SUSE:
                if self.config.target_arch == Architecture.X86_64:
                    path1 = '/usr/lib64/gio/modules/'
            # Arch
            elif self.config.target_distro == Distro.ARCH:
                path1 = '/usr/lib/gio/modules/'
            # Gentoo
            elif self.config.target_distro == Distro.GENTOO:
                path1 = '/usr/lib/gio/modules/'
            elif self.config.target_distro == Distro.NONE:
                if self.config.target_distro_version == DistroVersion.NONE_UCLIBC:
                    self.deps += ('gettext', 'libiconv')
            else:
                raise FatalError(_("Add specific for other Linux distributions here"))
            self._set_gio_flags(path1, path2, use_old_uri_scheme)

    def post_install(self):
        if self.config.target_platform == Platform.WINDOWS:
            shutil.copy(os.path.join(self.build_dir, 'glib', 'glibconfig.h.win32'),
                        os.path.join(self.config.prefix, 'lib', 'glib-2.0',
                                     'include', 'glibconfig.h'))
        if self.config.target_platform in [Platform.DARWIN, Platform.IOS]:
            # For the universal build we need to ship glibconfig.h of both
            # architectures in a subfolder and include the correct one depending
            # on the compiler architecture
            arch = self.config.target_arch
            if arch == Architecture.X86:
                arch = 'i386'
            elif arch == Architecture.ARM64:
                arch = 'arm64'
            elif Architecture.is_arm(arch):
                arch = 'arm'

            arch_dir = os.path.join(self.config.prefix, 'lib', 'glib-2.0',
                                     'include', arch)
            if not os.path.exists(arch_dir):
                os.makedirs(arch_dir)
            shutil.copyfile(os.path.join(self.build_dir, 'glib', 'glibconfig.h'),
                        os.path.join(arch_dir, 'glibconfig.h'))
            with open(os.path.join(self.config.prefix, 'lib', 'glib-2.0',
                                   'include', 'glibconfig.h'), 'w+') as f:
                f.write(GLIB_CONFIG_UNVERSAL)
